import 'dart:async';
import 'package:flutter/material.dart';
import 'package:x3_base_core/base_models/base_key_value_model.dart';
import 'package:x3_form_core/x3_form_core.dart';
import 'package:x3_component_core/x3_component_core.dart';
import 'package:x3_base_core/x3_base_core.dart';

/// mixin 等于 abstract --- on 等于 extends
mixin BusinessSelectMixin<T extends StatefulWidget> on State<T> {
  /// 标题
  String get title;

  /// 服务
  String get inputApi;

  /// 是否多选
  bool get isMulti;

  /// item
  Widget buildItem(Map<String, dynamic> item, int index);

  /// 选中的数据
  final List<BaseKeyValueModel> selectedList = [];

  List<String> get _selectedListKey => selectedList.map((e) => e?.key.toString()).toList();

  /// 控制数据列表
  final BaseRefreshController controller = BaseRefreshController();

  /// 控制合计
  final StreamController _streamController = StreamController<int>();

  /// 是否打开拍照
  bool get showScanIcon => false;

  /// 高级筛选请求参数
  BaseScreenRequestModel get filterRequestModel;

  /// 高级筛选数据处理
  BaseAdvancedFilterProvider initFilterDataSource(BaseHttpResultModel result);

  /// 参数
  Map<String, dynamic> get params => {};

  /// 初始数据
  List<BaseKeyValueModel> get initData;

  /// 搜索框关键字
  String get hintText => '请输入关键字搜索';

  /// 搜索框控制器
  final TextEditingController textController = TextEditingController();

  /// 扩展事件 用于被重写
  void initStateEvent() {}

  /// 显示搜索框
  bool get showSearchBar => true;

  String get businessTabEnum;

  /// 已有数据源
  List<BaseKeyValueModel> existingDataSource = [];

  /// 类型转换
  List<BaseKeyValueModel> typeConversion(List<Map<String, dynamic>> items);

  /// 点击全选
  bool isClickOnSelectAll = false;

  /// 高级筛选
  BaseAdvancedFilterProvider filterProvider;

  /// 开始生命周期
  @override
  void initState() {
    selectedList.addAll(initData);
    if (params.containsKey('searchKey')) {
      textController.text = params['searchKey'];
    }
    if (initStateEvent != null) initStateEvent();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return BaseScaffoldComponent(
      title: title,
      footerWidget: isMulti == true ? _footerWidget() : null,
      actions: [if (isMulti) TextButton(onPressed: onSelectAllEvents, child: Text(isClickOnSelectAll ? "取消全选" : "全选", style: Theme.of(context).appBarTheme.textTheme.headline1.copyWith(fontSize: 16)))],
      child: _buildDistinguish(),
    );
  }

  // 区分是否有高级筛选
  Widget _buildDistinguish() {
    if (this.filterRequestModel != null) return _buildAdvancedFilter();
    return _buildMainPart();
  }

  // 高级筛选
  Widget _buildAdvancedFilter() {
    return BaseScreenRefreshComponent(
        request: this.filterRequestModel,
        builder: (BaseHttpResultModel result) {
          if (filterProvider == null) filterProvider = this._initFilterDataSource(result);
          return _buildMainPart();
        });
  }

  // 主体部分
  Widget _buildMainPart() {
    return Column(
      children: [
        Visibility(
          visible: showSearchBar,
          child: BaseSearchFilterComponent.appBar(
            controller: textController,
            hintText: hintText,
            showScanIcon: showScanIcon,
            onFilterIconPress: this.filterRequestModel != null ? onFilterPress : null,
            onClearOut: () => {onSearch('')},
            onEditingComplete: onSearch,
          ),
        ),
        Expanded(
          child: BaseRefreshComponent(
            padding: EdgeInsets.only(bottom: 12),
            params: params,
            pageSize: 500,
            refreshDataLoadComplete: onExistingDataSource,
            dataLoadComplete: onExistingDataSource,
            controller: controller,
            path: inputApi,
            buildItem: buildItem,
          ),
        ),
      ],
    );
  }

  /// 底部按钮
  Widget _footerWidget() {
    return Container(
      color: Colors.white,
      child: BaseSelectorFooterStateBar(
        showCancel: false,
        stream: _streamController.stream,
        initialData: selectedList == null ? 0 : selectedList.length,
        onSure: onSure,
      ),
    );
  }

  /// 已有数据源
  void onExistingDataSource(List<Map<String, dynamic>> items, {bool isAddAll = false}) {
    if (isAddAll) {
      existingDataSource.clear();
      existingDataSource = typeConversion(items);
    } else {
      existingDataSource.addAll(typeConversion(items));
    }

    //初始化全选状态
    bool isInitState = isClickOnSelectAll;
    isClickOnSelectAll = true;
    existingDataSource.forEach((element) {
      int _isExist = selectedList.indexWhere((selectedListElement) => element.key == selectedListElement.key);
      if (_isExist == -1) isClickOnSelectAll = false;
    });
    if (isInitState != isClickOnSelectAll) setState(() {});
  }

  /// 全选按钮的全选事件
  void onSelectAllEvents() {
    isClickOnSelectAll = !isClickOnSelectAll;
    // 如果已选择列表里面没有则追加到列表后面
    existingDataSource.forEach((element) {
      int _isExist = selectedList.indexWhere((selectedListElement) => element.key == selectedListElement.key);
      if (isClickOnSelectAll) {
        if (_isExist == -1) selectedList.add(element);
      } else {
        if (_isExist != -1) selectedList.removeAt(_isExist);
      }
    });

    setState(() {});
    _streamController.sink.add(selectedList.length);
  }

  /// 选择
  void onChange(bool v, BaseKeyValueModel data) {
    isMulti == false ? _onChangeSingle(v, data) : _onChangeMulti(v, data);
  }

  bool isSelected(BaseKeyValueModel data) {
    return _selectedListKey.contains(data.key.toString());
  }

  /// 单选
  void _onChangeSingle(bool v, BaseKeyValueModel data) {
    Navigator.of(context).pop<BaseKeyValueModel>(data);
  }

  /// 多选
  void _onChangeMulti(bool v, BaseKeyValueModel data) {
    v == true ? selectedList.add(data) : selectedList.removeAt(_selectedListKey.indexOf(data.key.toString()));

    // 处理全选按钮显示问题
    if (v == true) {
      isClickOnSelectAll = true;
      existingDataSource.forEach((element) {
        int _isExist = selectedList.indexWhere((selectedListElement) => element.key == selectedListElement.key);
        if (_isExist == -1) isClickOnSelectAll = false;
      });
      setState(() {});
    } else {
      if (isClickOnSelectAll) {
        isClickOnSelectAll = false;
        setState(() {});
      }
    }
    _streamController.sink.add(selectedList.length);
  }

  /// 多选确定
  void onSure() {
    Navigator.of(context).pop<List<BaseKeyValueModel>>(this.selectedList);
  }

  /// 搜索事件
  void onSearch(String v) async {
    if (businessTabEnum != null && businessTabEnum.isNotEmpty && businessTabEnum == 'clothing') {
      BaseHttpResultModel resultModel = await dioUtil.fetch("/archive/clothing/v1/check/archive/$v/2", method: BaseHttpMethodEnum.GET);
      if (resultModel.success) {
        bool _status = BaseUtils.getKeyData(resultModel.data, "status", defaultValue: false);
        if (_status) {
          Map dataJson = BaseUtils.getKeyData(resultModel.data, "dataJson", defaultValue: {});
          String _styleId = BaseUtils.getKeyData(dataJson, "styleId", defaultValue: "");
          textController.text = _styleId;
          // 清除已有数据源
          existingDataSource.clear();
          controller.refresh(params: {'searchKey': _styleId}, isSearch: true);
          return;
        }
      }
    }
    // 清除已有数据源
    existingDataSource.clear();
    controller.refresh(params: {'searchKey': v}, isSearch: true);
  }

  /// 高级筛选 -----------------------------------
  // 高级筛选按钮点击事件
  void onFilterPress() {
    if (filterProvider == null) return;
    BaseFilterUtils.showAdvancedFilter(
      context,
      baseAdvancedFilterProvider: filterProvider,
      onComplete: (dynamic data) {
        // 清除已有数据源
        existingDataSource.clear();
        controller.refresh(params: data is Map ? data : {}, isSearch: true);
      },
    );
  }

  BaseAdvancedFilterProvider _initFilterDataSource(BaseHttpResultModel result) {
    if (this.initFilterDataSource != null) return this.initFilterDataSource(result);
    return BaseAdvancedFilterProvider(models: [], dataSource: {});
  }

  @override
  void dispose() {
    _streamController.close();
    super.dispose();
  }
}
